package spring.aop.cglibproxy;

import java.lang.reflect.Method;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

/**
 * @author GY
 * @date 2019年1月27日
 * @说明: CGLib动态代理
 */
public class ProxyHelp implements MethodInterceptor {
    @Override
    public Object intercept(Object obj, Method method, Object[] args,
            MethodProxy proxy) throws Throwable {
        // spring.aop.cglibproxy.A$$EnhancerByCGLIB$$26adae1a
        System.out.println(obj.getClass().getName());
        // say
        System.out.println(method.getName());
        // CGLIB$say$0 (say方法的代理方法，里面逻辑就是super.say(s))
        System.out.println(proxy.getSuperName());
        System.out.println("before");
        Object result = proxy.invokeSuper(obj, args);
        System.out.println("after");
        return result;
    }
    public static Object getProxy(Class<?> cls) {
        Enhancer enhancer =new Enhancer();
        enhancer.setSuperclass(cls);
        enhancer.setCallback(new ProxyHelp());
        return enhancer.create();
    }
    public static Object getMyProxy() {
        MyCGLibProxy myCGLibProxy = new MyCGLibProxy(new ProxyHelp());
        return myCGLibProxy;
    }
}
